﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using System.Web.Security;
using DataAccess;

namespace admin
{
	public partial class admin_Newreport : Page
	{
		String surveydate;
		bool lastcomponent;
		int componentID;
		ComponentStatus previousComponentStatus;
		private DataTable listOfcomments;
		int machineid;
	    private bool isModifyReport;

	    protected void Page_Load(object sender, EventArgs e)
		{
			String componentname = Request.QueryString["componentname"];
			String machinename = Request.QueryString["machinename"];
			machineid = Int32.Parse(Request.QueryString["machineid"]);
			componentID = Int32.Parse(Request.QueryString["componentID"]);
			lastcomponent = bool.Parse(Request.QueryString["lastcomponent"]);
		    string isModifyReportParameter = Request.QueryString["IsModifyReport"];
		    if (isModifyReportParameter != null)
		    {
		        string reportDate = Request.QueryString["ReportDate"];
                isModifyReport = bool.Parse(isModifyReportParameter);
		        if (isModifyReport)
		        {
		            Title.Text = String.Format("Modify Report on {0}", reportDate);
		            lblPreviousReport.Text = "Report on";
		            submit_button.Text = "Update";
		        }
		    }
			if (!lastcomponent)
			{
				DropDownList_Matrix.Visible = false;
				matrix_label.Visible = false;
				Matrix_Textbox.Visible = false;
			}
			surveydate = (String)Session["SurveyDate"];
			Pre_date.Text = "";
			if (!IsPostBack)
			{
				tablePanel.Style.Add("display", "none");
				componentLabel.Text = machinename + "------" + componentname;
				Comment cmt = new Comment();
				previousComponentStatus = cmt.GetPreviousRecomm(componentID, surveydate);
				listOfcomments = cmt.GetComments(componentID);
				if (listOfcomments != null && listOfcomments.Rows.Count > 0)
				{
					dropdownlist_comment.DataSource = listOfcomments;
					dropdownlist_comment.DataBind();

				}
				else
				{
					ListItem noresult = new ListItem("No Result Found!", "6");
					dropdownlist_comment.Items.Clear();
					dropdownlist_comment.Items.Add(noresult);
				}
				if (!dropdownlist_comment.SelectedValue.Equals("6"))
				{
					this.Comment_tb.Text = dropdownlist_comment.Text;
				}

				if (previousComponentStatus != null)
				{
				    String historyDate = previousComponentStatus.dateRecorded.ToString("dd/MM/yyyy");
					Pre_date.Text = historyDate;
				    PreviousComment.Text = previousComponentStatus.comments;
				}
				else
				{
					PreviousComment.Text = "Not Avaiable";
				}
				addFaultlist(1, 0);
				addFaultlist(1, 1);
				addFaultlist(1, 2);
				cmt = new Comment();
				DataTable dtResury = cmt.getResurvey();
				foreach (DataRow dr in dtResury.Rows)
				{
					String resuryid = dr["resurvey_id"].ToString();
					string resurydes = dr["resurvey_des"].ToString();
					ListItem resurveyitem = new ListItem(resurydes, resuryid, true);
					Resurvey_DropDownList.Items.Add(resurveyitem);
				}
			}
		}

		public void addFaultlist(int faulttype, int FaultListID)
		{
			var cmt = new Comment();
			DataTable dt = cmt.getFaults(componentID);
			foreach (DataRow dr in dt.Rows)
			{
				string faultid = dr["fault_id"].ToString();
				String faultname = dr["faultName"].ToString();
				ListItem clienitem = new ListItem(faultname, faultid, true);
				if (FaultListID == 0)
				{
					Fault1_DropDownList.Items.Add(clienitem);
				}
				else if (FaultListID == 1)
				{
					Fault2_DropDownList.Items.Add(clienitem);
				}
				else
				{
					Fault3_DropDownList.Items.Add(clienitem);
				}

			}
		}

		protected void submit_button_Click(object sender, EventArgs e)
		{
			if (!Page.IsValid)
			{
			}
			else
			{
			    try
			    {
                    var cmt = new Comment();
			        if (isModifyReport)
			        {
                        cmt.RemoveCurrentComment(componentID, surveydate);
			        }
			        if (CheckBox_oldreport.Checked)
			        {
			            previousComponentStatus = cmt.GetPreviousRecomm(componentID, surveydate);
			            cmt.insertNewreport(componentID, previousComponentStatus);
                        return;
			        }
			        if (this.HiddenControl1.Value == "none")
			        {
			            string commentBeforeEdited = dropdownlist_comment.SelectedValue;
			            if (!commentBeforeEdited.Equals("6"))
			            {
			                surveydate = (String) Session["SurveyDate"];
			                cmt = new Comment();
			                var cmtItem = cmt.GetComments(commentBeforeEdited, componentID);
			                cmt.insertNewreport(componentID, cmtItem.status_id, commentBeforeEdited, surveydate,
			                    cmtItem.recommendId_1, cmtItem.recommendId_2, cmtItem.recommendId_3, cmtItem.resurvey_Id);
			                Response.Write("<script language=javascript> alert('New Comment Added')</script>");
			            }
			        }
			        else
			        {
			            int Recom1_id = 0, Recom2_id = 0, Recom3_id = 0;
			            Recom1_id = GetReco1();
			            Recom2_id = GetReco2();
			            Recom3_id = GetReco3();
			            if (Recom1_id == 0 && Recom2_id == 0 && Recom3_id == 0)
			            {
			                Response.Write(@"<script language='javascript'>alert('No faults being selected')</script>");
			                return;
			            }
			            int severityID = Int32.Parse(Severity1_DropDownList.SelectedValue);
			            int severity2ID = 0, severity3ID = 0;
			            int resurvyID = Int32.Parse(Resurvey_DropDownList.SelectedItem.Value);
			            severity3ID = Int32.Parse(Severity3_DropDownList.SelectedValue);
			            severity2ID = Int32.Parse(Severity2_DropDownList.SelectedValue);
			            Comment ct = new Comment();
			            severityID = getSeverity(severityID, severity2ID, severity3ID);
			            bool result = ct.insertNewreport(componentID, severityID, Comment_tb.Text, surveydate, Recom1_id,
			                Recom2_id, Recom3_id, resurvyID);
			            if (lastcomponent)
			            {
			                ct = new Comment();
			                int matrix = Int32.Parse(Matrix_Textbox.Text);
			                ct.InsertMatrix(surveydate, machineid, matrix);
			            }
			            if (result)
			            {
			                Response.Write("<script language=javascript> alert('success')</script>");
			            }
			            else
			            {
			                Response.Write("<script language=javascript> alert('failed')</script>");
			            }
			        }
			    }
			    catch (Exception ex)
			    {
			        Response.Write(ex);
			    }
			    finally
			    {
			        
			    }

			}
		}

		private int GetReco3()
		{
		Comment cmt = new Comment();
			if(Fault3_DropDownList.SelectedIndex !=0 && Severity3_DropDownList.SelectedIndex != 0)
			{	   
				int faultID,statusId;
				Int32.TryParse(Fault3_DropDownList.SelectedValue,out faultID);
				Int32.TryParse(Severity3_DropDownList.SelectedValue, out statusId);
				return cmt.GetRecomId(faultID, statusId);
			} 
			return 0;
		}

		private int GetReco2()
		{
		Comment cmt = new Comment();
			if(Fault2_DropDownList.SelectedIndex !=0 && Severity2_DropDownList.SelectedIndex != 0)
			{	   
				int faultID,statusId;
				Int32.TryParse(Fault2_DropDownList.SelectedValue,out faultID);
				Int32.TryParse(Severity2_DropDownList.SelectedValue, out statusId);
				return cmt.GetRecomId(faultID, statusId);
			} 
			return 0;
		}

		private int GetReco1()
		{
		Comment cmt = new Comment();
			if(Fault1_DropDownList.SelectedIndex !=0 && Severity1_DropDownList.SelectedIndex != 0)
			{	   
				int faultID,statusId;
				Int32.TryParse(Fault1_DropDownList.SelectedValue,out faultID);
				Int32.TryParse(Severity1_DropDownList.SelectedValue, out statusId); 
				return cmt.GetRecomId(faultID, statusId);
			} 
			return 0;
		}

		public int getSeverity(int id1, int id2, int id3)
		{
			int severity;
			if (id2 == 0)
			{//only one fault chosen
				severity = id1;
			}
			else if (id3 == 0)
			{//two faults chosen
				severity = id1 > id2 ? id1 : id2;
			}
			else
			{//three faults chosen;
				severity = id1 > id2 ? (id1 > id3 ? id1 : id3) : (id2 > id3 ? id2 : id3);
			}
			return severity;
		}

		protected void ServerValidate(object source, ServerValidateEventArgs args)
		{
			int input;
			int severity = Int32.Parse(DropDownList_Matrix.SelectedValue);
			bool parseOk = int.TryParse(args.Value, out input);
			switch (severity)
			{

				case 1: args.IsValid = parseOk && (input > 0 && input <= 75); break;
				case 2: args.IsValid = parseOk && (input > 75 && input <= 100); break;
				case 3: args.IsValid = parseOk && (input > 100 && input <= 125); break;
				case 4: args.IsValid = parseOk && (input > 125 && input <= 150); break;
				case 5: args.IsValid = parseOk && (input > 0 && input <= 150); break;
			}
		}

		protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
		{
			Session.Contents.Remove("UserDetails");
			Session.Abandon();
			Session.Contents.RemoveAll();
			FormsAuthentication.SignOut();
			Response.Redirect("../Default.aspx");
		}

		protected void statusChanged(object sender, EventArgs e)
		{
			int statusSelected = Int32.Parse(dropdownlist_status.SelectedValue);
			Comment cmt = new Comment();
			DataTable dt;
			if(statusSelected == 0)
			{
				dt = cmt.GetComments(componentID);
			}else
			{
				dt = cmt.GetCommentsByStatusId(componentID, statusSelected);
			}
			if (dt != null && dt.Rows.Count > 0)
			{
				dropdownlist_comment.DataSource = dt;
				dropdownlist_comment.DataBind();
			}
			else
			{
				ListItem noresult = new ListItem("No Result Found! Create a new comment below", "6");
				dropdownlist_comment.Items.Clear();
				dropdownlist_comment.Items.Add(noresult);
				tablePanel.Visible = true;
			}
			CommentChanged(null, null);
		}

		protected void CommentChanged(object sender, EventArgs e)
		{
			if (!dropdownlist_comment.SelectedValue.Equals("6"))
			{
				this.Comment_tb.Text = dropdownlist_comment.Text;
			}
			else
			{
				this.Comment_tb.Text = "";
			}
		}
	}
}
